package com.example.stock.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.example.stock.config.Config;
import com.example.stock.model.GoodsData;
import com.example.stock.model.GoodsOrderBean;
import com.excel.greendao.DaoMaster;
import com.excel.greendao.DaoSession;
import com.excel.greendao.GoodsDataDao;
import com.excel.greendao.GoodsOrderBeanDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

public class DBUtil {
    private static final String DB_NAME = "stock.db";
    private DaoMaster sDaoMaster;
    private DaoSession sDaoSession;
    private Context context;
    @SuppressLint("StaticFieldLeak")
    private static DBUtil instance;


    public static DBUtil getInstance() {
        if (instance == null) {
            synchronized (DBUtil.class) {
                if (instance == null) {
                    instance = new DBUtil();
                }
            }
        }
        return instance;
    }

    private DBUtil() {
    }

    public void init(Context context) {
        this.context = context;
        getDaoMaster();
        getDaoSession();
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
    }

    /**
     * 判断是否有存在数据库，如果没有则创建
     */
    public DaoMaster getDaoMaster() {
        if (sDaoMaster == null) {
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
            sDaoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return sDaoMaster;
    }

    /**
     * 完成对数据库的添加、删除、修改、查询操作，仅仅是一个接口
     */
    public DaoSession getDaoSession() {
        if (sDaoSession == null) {
            if (sDaoMaster == null) {
                sDaoMaster = getDaoMaster();
            }
            sDaoSession = sDaoMaster.newSession();
        }
        return sDaoSession;
    }

    public boolean insetEX(List<GoodsOrderBean> list) {
        if (list == null || list.size() == 0) return false;
        for (GoodsOrderBean orderBean : list) {
            long insert = sDaoSession.getGoodsOrderBeanDao().insert(orderBean);
            if (insert < 0) {
                clearAll();
                Config.LogI("insert GoodsOrderBean error. ");
                return false;
            }
            if(orderBean.getDataList() != null){
                for (GoodsData data : orderBean.getDataList()) {
                    data.setDjh(orderBean.getDjh());
                    data.setGysName(orderBean.getGysName());
                    if(TextUtils.isEmpty(data.getPcCode())) {
                        data.setPcCode("temp");
                    }
                    long insert1 = sDaoSession.getGoodsDataDao().insert(data);
                    if (insert1 < 0) {
                        clearAll();
                        Config.LogI("insert GoodsData error.");
                        return false;
                    }
                }
            }
        }
        Config.LogI("insert data. ");
        return true;
    }

    /**
     * lt：小于 le：小于等于
     * gt：大于 ge：大于等于
     * eq：等于
     * @param goodsOrderBean
     * @param indexType
     * @param offset
     * @return
     */
    public List<GoodsData> queryGoodsDataByDjh(GoodsOrderBean goodsOrderBean, int indexType, int offset) {
        int type = indexType == 0 ?  1 : 0;
        return sDaoSession.getGoodsDataDao()
                .queryBuilder()
                .where(GoodsDataDao.Properties.Djh.eq(goodsOrderBean.getDjh()), GoodsDataDao.Properties.Type.eq(type))
                .offset(offset * Config.PAGE_SIZE).limit(Config.PAGE_SIZE)
                .build()
                .list();
    }

    public GoodsData query(GoodsData goodsData) {
        return sDaoSession.getGoodsDataDao()
                .queryBuilder()
                .where(GoodsDataDao.Properties.Djh.eq(goodsData.getDjh()))
                .build()
                .unique();
    }

    public List<GoodsOrderBean> queryGoodsOrderAll() {
        return sDaoSession.getGoodsOrderBeanDao().queryBuilder()
                .where(GoodsOrderBeanDao.Properties.IsUpload.eq("0")).build().list();
    }

    public boolean clearAll() {
        boolean flag = false;
        try {
            if (sDaoSession != null) {
                sDaoSession.getGoodsOrderBeanDao().deleteAll();
                sDaoSession.getGoodsDataDao().deleteAll();
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public List<GoodsData> queryGoodsDataByCode(GoodsOrderBean orderBean, GoodsData code) {
        return sDaoSession.getGoodsDataDao()
                .queryBuilder()
                .where(GoodsDataDao.Properties.Djh.eq(orderBean.getDjh()),
                        GoodsDataDao.Properties.Invcode.eq(code.getInvcode()))
                .build()
                .list();
    }

    public void update(GoodsData inventoryBean) {
        sDaoSession.getGoodsDataDao().update(inventoryBean);
    }

    public void update(GoodsOrderBean goodsOrderBean) {
        sDaoSession.getGoodsOrderBeanDao().update(goodsOrderBean);
    }
}
